import * as signalR from "@microsoft/signalr";
import store from "index/store";
class Connection {
  constructor() {
    this.msgStack = new Map();
    // 正式修改 --end
    this.connect = null;
    this.state = false;
    this.timeout = null;
    this.callbacks = new Map();
    this.firstGet = true;
  }
  init() {
    this.connect = new signalR.HubConnectionBuilder()
      .withUrl("/signalr-hubs/messaging", {
        accessTokenFactory: () => {
          return store.state.token.slice(7);
        }
      })
      .build();
    this.connect.on("ReceiveMessageCount", data => {
      console.log("消息更新：",data);
      this.msgStack.forEach(fn => {
        fn(data);
      });
    });
  }
  addMsgListen(id, fn) {
    return new Promise(resolve => {
      this.msgStack.set(id, fn);
      resolve(id);
    });
  }
  removeMsgListen(id) {
    this.msgStack.delete(id);
  }
  start() {
    this.init();
    this.connect
      .start()
      .then(() => {
        console.log("连接成功！");
        this.state = true;
      })
      .catch(() => {
        console.log("连接失败");
      });
  }
  ready(fn) {
    if (fn) {
      const id = Symbol();
      this.callbacks.set(id, fn);
    }
    if (!this.state) {
      this.timeout && clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.ready();
      }, 400);
      return;
    }
    if (this.firstGet) {
      this.firstGet = false;
      this.callbacks.size && this.callbacks.forEach(fn => fn());
    } else {
      this.callbacks.size && this.callbacks.forEach(fn => fn());
    }
  }
}
const connection = new Connection();
export default connection;

/**
 * 调用方式
 * 1. main.js添加引用
      import connect from "@/utils/signalR";
      Vue.prototype.$connect = connect;
 * 2. vue主页建立连接
      登录后调用this.$connect.start();
 * 3. vue内页绑定回调函数，例：绑定位置更新
      getPositionDatas(data){},
      bindSocket(){
        let key;
        this.$connect.addPosition(this.getPositionDatas).then(id => {
          key = id;
        });
        // 页面销毁前删除绑定
        this.$once("hook:beforeDestroy", () => {
          this.$connect.removePosition(key);
        });
      }
 */
